package com.toune.movie.base.myview;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.toune.movie.R;
import com.toune.movie.base.AppConstant;
import com.toune.movie.base.myUtil.MyUtil;
import com.toune.movie.vo.DownVo;
import com.toune.movie.vo.MusicVo;
import com.vondear.rxtool.RxAppTool;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.RxFileTool;
import com.vondear.rxtool.RxTool;
import com.vondear.rxtool.view.RxToast;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadRequest;

import java.io.File;

/**
 * Created by Administrator on 2018/4/17.
 */

public class DownLoadDialog extends Dialog {
    private Context context;
    private Button cancelBtn, backBtn;
    private NumberProgressBar mProgressBar;

    //    private String url = "http://gdown.baidu.com/data/wisegame/00d935b62e77cfc1/weixin_780.apk";
    private DownloadRequest downloadRequest;//下载请求
    private static final String CancelSign = "CancelSign";
    private MusicVo.DataBean downVo;

    public DownLoadDialog(Context context, MusicVo.DataBean downVo) {
        super(context);
        this.context = context;
        this.downVo = downVo;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = this.getWindow();
        window.setGravity(17);
        window.setWindowAnimations(com.siberiadante.customdialoglib.R.style.bottom_animation);

        View view = View.inflate(context, R.layout.dialog_download_apk, null);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(view);
        WindowManager windowManager = ((Activity) context).getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.width = display.getWidth() * 4 / 5;
        this.getWindow().setAttributes(lp);
        this.setCanceledOnTouchOutside(false);

        mProgressBar = view.findViewById(R.id.numberProgressBar);
        backBtn = view.findViewById(R.id.bacBtn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        cancelBtn = view.findViewById(R.id.cancelBtn);
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                downloadRequest.cancel();
            }
        });
        //下载文件
        //说明一下下面的几个参数
        //1.url
        //2.文件存储路径
        //3.文件名
        //4.断点是否继续
        //5.是否删除旧的
        downloadRequest = NoHttp.createDownloadRequest(downVo.getUrl(),
                MyUtil.getAppMusicPath(),
                downVo.getTitle() + "~" + downVo.getAuthor() + ".mp3",
                true,
                true);
        downloadRequest.setCancelSign(CancelSign);//设置停止下载的记号
        down();
    }

    private void stop() {
        downloadRequest.cancelBySign(CancelSign);//通过记号停止下载
    }

    private int WHAT = 0;

    private void down() {
        check();
        NoHttp.getDownloadQueueInstance().add(WHAT, downloadRequest, new DownloadListener() {
            @Override
            public void onDownloadError(int what, Exception exception) {
                //下载异常
            }

            @Override
            public void onStart(int what, boolean isResume, long rangeSize, Headers responseHeaders, long allCount) {
                //开始下载
                //what
                //isResume 是否重新下载
                //rangeSize 已下载文件大小
                //responseHeaders
                //allCount 文件总大小
                //int progress = (int) (rangeSize * 100 / allCount); 下载进度
                int progress = (int) (rangeSize * 100 / allCount); //下载进度
                mProgressBar.setProgress(progress);
            }

            @Override
            public void onProgress(int what, int progress, long fileCount, long speed) {
                mProgressBar.setProgress(progress);
            }


            @Override
            public void onFinish(int what, String filePath) {
                //下载完成
                //filePath 文件路径
                dismiss();
                RxToast.success("文件已下载到" + filePath + "文件夹中");
                AVObject avObject = new AVObject(AppConstant.TAB_DOWN_HIS);
                if (AVUser.getCurrentUser() != null) {
                    avObject.put("userId", AVUser.getCurrentUser().getObjectId());
                }
                avObject.put("url", downVo.getUrl());
                avObject.put("fileName", downVo.getTitle() + "~" + downVo.getAuthor() + ".mp3");
                avObject.put("authorName", downVo.getAuthor());
                avObject.put("phoneId", RxDeviceTool.getUniqueSerialNumber());
                avObject.put("localPath", filePath);
                avObject.put("imgUrl", downVo.getPic());
                avObject.put("lrc", downVo.getLrc());
                avObject.put("link", downVo.getLink());
                avObject.put("songId", downVo.getSongid());
                avObject.saveInBackground();
            }

            @Override
            public void onCancel(int what) {
                //下载取消
                stop();
            }
        });
    }


    private void check() {
        // 检查之前的下载状态
        int beforeStatus = downloadRequest.checkBeforeStatus();
        switch (beforeStatus) {
            case DownloadRequest.STATUS_RESTART:
                mProgressBar.setProgress(0);
                RxToast.showToast("开始下载");
                break;
            case DownloadRequest.STATUS_RESUME:
                RxToast.showToast("正在下载");
                break;
            case DownloadRequest.STATUS_FINISH:
                mProgressBar.setProgress(100);
                RxToast.showToast("下载完成");
                break;
        }
    }
}
